package com.zy.openchat.core.manager;

import android.content.Context;
import android.content.SharedPreferences;

import com.blankj.utilcode.util.ActivityUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.zy.openchat.App;
import com.zy.openchat.Constants;

import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

public class AuthUserManager {
    private volatile static AuthUserManager authUserManager;
    private List<AuthUserInfo> authUsersList = new ArrayList<>();

    private AuthUserManager() {
        load();
    }

    public static AuthUserManager getAuthUserManager() {
        if (authUserManager == null) {
            synchronized (AuthUserManager.class) {
                if (authUserManager == null) {
                    authUserManager = new AuthUserManager();
                }
            }
        }
        return authUserManager;
    }

    private void load() {
        List<AuthUserInfo> list = getAuthUsers();
        if (list == null) {
            list = new ArrayList<>();
        }
        authUsersList = list;
    }

    //当前登录用户，可能为空
    public AuthUserInfo currentAuthUser() {
        for (AuthUserInfo auth : authUsersList) {
            if (auth.isCurrentLoginUser) {
                return auth;
            }
        }
        return null;
    }

    //根据号码获取认证用户信息，可能为空
    public AuthUserInfo authUser(String phone) {
        if (!StringUtils.isEmpty(phone)) {
            for (AuthUserInfo auth : authUsersList) {
                if (auth.isThisPhone(phone)) {
                    return auth;
                }
            }
        }
        return null;
    }

    private AuthUserInfo authUserFromDirectory(String data_directory) {
        if (!StringUtils.isEmpty(data_directory)) {
            for (AuthUserInfo auth : authUsersList) {
                if (data_directory.equals(auth.data_directory)) {
                    return auth;
                }
            }
        }
        return null;
    }

    //除当前登录用户之外，用户列表
    public List<AuthUserInfo> authListWithoutCurrentAuthUser() {
        List<AuthUserInfo> list = new ArrayList<>();
        for (AuthUserInfo auth : authUsersList) {
            if (!auth.isCurrentLoginUser) {
                list.add(auth);
            }
        }
        return list;
    }

    //初始化一个数据目录
    public static String create_data_directory() {
        return UUID.randomUUID().toString();
    }

    public static String data_directoryPath(String data_directory) {
        return Constants.authUserRootPath() + data_directory + File.separator;
    }

    private void resetAllUserLogout() {
        for (AuthUserInfo auth : authUsersList) {
            if (auth.isCurrentLoginUser) {
                auth.lastLoginTime = new Date().getTime();
                auth.isCurrentLoginUser = false;
            }
        }
    }

    private void handleMultiOnline(){
        TelegramManager.getTelegramManager().getMultiOnline(null, new TgResultBlock<Boolean>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, Boolean obj) {
                if(!obj){
                    TelegramManager.getTelegramManager().terminateAllOtherSessions(ActivityUtils.getTopActivity(), new TgResultBlock<TgResponse>() {
                        @Override
                        public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {

                        }

                        @Override
                        public void onTimeout(Map<String, Object> request) {

                        }
                    });
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {

            }
        });
    }

    //用户-登录
    public void login(String phone, String data_directory) {
        handleMultiOnline();
        resetAllUserLogout();
        AuthUserInfo curUser_Directory = authUserFromDirectory(data_directory);
        if (curUser_Directory != null) {
            if (curUser_Directory.isThisPhone(phone)) {//同一个
                curUser_Directory.lastLoginTime = new Date().getTime();
                curUser_Directory.isCurrentLoginUser = true;
            } else {//不是同一个
                AuthUserInfo curUser = authUser(phone);
                if (curUser != null) {
                    authUsersList.remove(curUser);
                }
                curUser_Directory.phone = phone;
                curUser_Directory.userId = 0;
                curUser_Directory.lastLoginTime = new Date().getTime();
                curUser_Directory.isCurrentLoginUser = true;
            }
        } else {
            AuthUserInfo curUser = authUser(phone);
            if (curUser != null) {
                curUser.data_directory = data_directory;
                curUser.lastLoginTime = new Date().getTime();
                curUser.isCurrentLoginUser = true;
            } else {
                curUser = new AuthUserInfo();
                curUser.userId = 0;
                curUser.phone = phone;
                curUser.data_directory = data_directory;
                curUser.lastLoginTime = new Date().getTime();
                curUser.isCurrentLoginUser = true;
                authUsersList.add(curUser);
            }
        }
        saveAuthUsers(authUsersList);
    }

    //更新当前用户userid
    public void updateCurrentUserId(long userId) {
        AuthUserInfo curUser = currentAuthUser();
        if (curUser != null && curUser.userId == 0) {
            curUser.userId = userId;
            saveAuthUsers(authUsersList);
        }
    }

    //更新当前用户phone
    public void updateCurrentUserPhone(String phone) {
        if (!StringUtils.isEmpty(phone)) {
            AuthUserInfo curUser = currentAuthUser();
            if (curUser != null) {
                curUser.phone = phone;
                saveAuthUsers(authUsersList);
            }
        }
    }

    //当前用户-退出登录
    public void logout() {
        AuthUserInfo cur = currentAuthUser();
        if (cur != null) {
            authUsersList.remove(cur);
            resetAllUserLogout();
            saveAuthUsers(authUsersList);
        }
    }

    //登录新账号
    public void loginOtherAccount() {
        resetAllUserLogout();
        saveAuthUsers(authUsersList);
    }

    //清理垃圾数据-登录成功时进行
    public static void cleanDestroyFolder() {

    }

    private List<AuthUserInfo> getAuthUsers() {
        Context context = App.getInstanse();
        String jsonStr = context.getSharedPreferences("GoChatAuthUsers", Context.MODE_PRIVATE).getString("users", null);
        if (jsonStr != null)
            return new ArrayList<>(Arrays.asList(new Gson().fromJson(jsonStr, AuthUserInfo[].class)));
        return null;
    }

    private void saveAuthUsers(List<AuthUserInfo> list) {
        if (list == null) {
            return;
        }
        String jsonStr = new Gson().toJson(list);
        Context context = App.getInstanse();
        SharedPreferences.Editor editor = context.getSharedPreferences("GoChatAuthUsers", Context.MODE_PRIVATE).edit();
        editor.putString("users", jsonStr);
        editor.apply();
    }
}